(() => {
    DevExpress.localization.locale("zh");

    $.fn.datepicker.dates = {};

    $(document).ajaxError((event, jqXHR) => {
        if (jqXHR.status === 401) {
            // 如果状态码为 401，跳转到登录页面
            window.location.reload();
        } else {
            console.error('AJAX error:', jqXHR);
        }
    });

    class Ris {
        permissions = [];
        settings = [];

        get host() {
            return window.chrome?.webview?.hostObjects?.host;
        }

        async initialize() {
            await this.loadPermissions();
            await this.loadSettings();
        }

        loadPermissions() {
            return new Promise((resolve, reject) => {
                $.get('/api/get-permissions').then(result => {
                    this.permissions = result;
                    resolve();
                });
            });
        }

        loadSettings() {
            return new Promise((resolve, reject) => {
                $.get('/api/get-settings').then(result => {
                    this.settings = result;
                    resolve();
                });
            });
        }

        getCookie(name) {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                // 检查是否是目标 cookie
                if (cookie.startsWith(name + '=')) {
                    return cookie.substring(name.length + 1);
                }
            }
            // 未找到目标 cookie
            return null;
        }

        getSetting(name) {
            return this.settings.find(x => x.name == name)?.value;
        }

        setSetting(name, value, type) {
            const setting = this.settings.find(x => x.name == name);
            if (!setting) {
                this.settings.push({ name, value });
            } else {
                setting.value = value;
            }
            return new Promise((resolve, reject) => {
                $.post('/api/set-setting', { name, value, type }).then(result => {
                    resolve(result);
                });
            });
        }

        getConfigValue(name) {
            return window.chrome?.webview?.hostObjects?.sync?.host?.getConfigValue(name);
        }

        getStationCode() {
            let stationCode = this.getCookie('StationCode');
            return stationCode ?? this.getConfigValue('StationCode');
        }

        async hasPlugin(pluginName) {
            if (this.host?.hasPlugin instanceof Function) {
                return await this.host.hasPlugin(pluginName);
            }
            return null;
        }

        invokePlugin(pluginName, pluginParams, waitForExit, onWindow) {
            return new Promise((resolve, reject) => {
                if (this.host) {
                    this.host.invokePlugin(pluginName, pluginParams, waitForExit, onWindow).then(result => {
                        result = JSON.parse(result);
                        if (result.success) {
                            resolve(result.data);
                        } else {
                            reject(result.error);
                        }
                    }).catch(reject);
                } else {
                    reject();
                }
            });
        }

        verify(name) {
            return this.permissions.includes(name);
        }

        formatDateTime(e) {
            return luxon.DateTime.fromJSDate(new Date(e)).toFormat('yyyy-MM-dd HH:mm:ss');
        }

        printReport(url) {
            if (this.host) {
                this.host.printPdf(url, 'Report');
            } else {
                window.open(url, '_blank');
            }
        }

        viewReport(url) {
            window.open(url, '_blank');
        }

        viewImage(url) {
            if (this.host) {
                let screen = 2;
                let imageScreen = this.getConfigValue('ImageScreen');
                if (imageScreen) {
                    screen = parseInt(imageScreen);
                    if (screen === NaN) {
                        screen = 2;
                    }
                }
                url += url.indexOf('?') ? '&' : '?';
                url += `--new-window=screen=${screen},full-screen=true`;
            }
            window.open(url, 'dicom-image-viewer');
        }

        showLoading() {
            if (window.yakeji?.showLoading) {
                window.yakeji.showLoading();
            }
        }

        hideLoading() {
            if (window.yakeji?.hideLoading) {
                window.yakeji.hideLoading();
            }
        }

        clearCache() {
            window.localStorage.clear();
            window.sessionStorage.clear();
        }

        changePassword() {
            $('<div class="change-password-form" />').dxForm({
                formData: {
                    currentPassword: '',
                    newPassword: '',
                    confirmPassword: ''
                },
                items: [{
                    dataField: 'currentPassword',
                    label: { text: '当前密码' },
                    editorType: 'dxTextBox',
                    editorOptions: {
                        mode: 'password'
                    },
                }, {
                    dataField: 'newPassword',
                    label: { text: '新的密码' },
                    editorType: 'dxTextBox',
                    editorOptions: {
                        mode: 'password'
                    },
                }, {
                    dataField: 'confirmPassword',
                    label: { text: '确认密码' },
                    editorType: 'dxTextBox',
                    editorOptions: {
                        mode: 'password'
                    },
                    validationRules: [{
                        type: 'compare',
                        comparisonTarget: () => $('.change-password-form').dxForm('instance').option('formData').newPassword,
                        message: '两次输入的密码不一致'
                    }]
                }],
            }).formPopup({
                title: '更改密码',
                maxWidth: 600,
                maxHeight: 400,
                callback: (value, closePopup) => {
                    $.post('/api/change-password', value).then(result => {
                        if (result.success) {
                            DevExpress.ui.notify('密码已更改', 'success', 1000);
                            closePopup();
                        } else {
                            DevExpress.ui.notify(result.error, 'error', 1000);
                        }
                    });
                }
            });
        }

        validateExam(examId, type) {
            return new Promise((resolve, reject) => {
                this.showLoading();
                $.ajax(`/api/exam/validate`, { data: { examId, type }, type: 'POST' }).then(result => {
                    this.hideLoading();
                    if (result.success && result.data) {
                        let hasWarn = false;
                        let hasError = false;
                        const $message = $('<div class="exam-validation-result" />');
                        for (const level in result.data) {
                            for (const message of result.data[level]) {
                                switch (level) {
                                    case 'Info':
                                        $message.append(
                                            $('<div class="info result-item" />')
                                                .append($(`<i class="icon fa fa-info-circle" />`))
                                                .append($(`<span class="message">${message}</span>`)
                                                )
                                        );
                                        break;
                                    case 'Warn':
                                        hasWarn = true;
                                        $message.append(
                                            $('<div class="warn result-item" />')
                                                .append($(`<i class="icon fa fa-warning" />`))
                                                .append($(`<span class="message">${message}</span>`)
                                                )
                                        );
                                        break;
                                    case 'Error':
                                        hasError = true;
                                        $message.append(
                                            $('<div class="error result-item" />')
                                                .append($(`<i class="icon fa fa-times-circle" />`))
                                                .append($(`<span class="message">${message}</span>`)
                                                )
                                        );
                                        break;
                                }
                            }
                        }
                        if ($message.children.length > 0) {
                            if (hasError) {
                                $message.addClass('has-error');
                                DevExpress.ui.dialog.alert($message.prop('outerHTML'), '错误');
                            } else if (hasWarn) {
                                const messageHtml = $message.append(
                                    $('<div class="tip" />')
                                        .append($('<i class="icon fa fa-info-circle" />'))
                                        .append($('<span class="message" />').text('验证时出现了警告，是否继续')))
                                    .prop('outerHTML');
                                DevExpress.ui.dialog.confirm(messageHtml, '警告').then(result => result && resolve());
                            } else {
                                DevExpress.ui.dialog.alert($message.prop('outerHTML'), '提示').then(resolve);
                            }
                        }
                    }
                    else {
                        resolve();
                    }
                }).catch(() => {
                    this.hideLoading();
                    reject();
                });
            });
        };

        ajax(url, options) {
            return new Promise(resolve => {
                options = options || {};
                if (options.dataType?.toLowerCase() === 'json') {
                    if (options.data) {
                        options.data = JSON.stringify(options.data);
                        options.contentType = 'application/json;charset=UTF-8';
                    }
                }
                this.showLoading();
                $.ajax({
                    url,
                    type: 'GET',
                    success: result => {
                        this.hideLoading();
                        if (result.success) {
                            resolve(result);
                        } else {
                            DevExpress.ui.notify(result.error || '接口请求失败', 'error');
                        }
                    },
                    error: (error) => {
                        this.hideLoading();
                        DevExpress.ui.notify(options.errorMessage || '接口请求失败', 'error');
                    },
                    ...options
                });
            })
        };

        downFile(url, fileName, options) {
            const x = new XMLHttpRequest();
            x.open(options.method ?? 'POST', url, true);
            x.responseType = 'blob';
            x.setRequestHeader('Content-Type', options.contentType ?? 'application/json;charset=UTF-8');
            x.onload = function () {
                if (x.status === 200) {
                    const url = window.URL.createObjectURL(x.response);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = fileName;
                    a.click();
                    URL.revokeObjectURL(url);
                }
            };
            x.onreadystatechange = function () {
                if (x.status !== 200) {
                }
            }
            //如果有数据，则发送数据; 否则发送空字符串
            x.send(options.data ? JSON.stringify(options.data) : '');
        };
    }

    window.ris = new Ris();
    window.getUrlSearch = (key) => {
        var reg = new RegExp('[\?\&]' + key + '=([^\&]*)(\&?)', 'i');
        let value = window.location.search.match(reg);
        if (!value) return null;
        return value[1];
    }

    if (window.ris.host) {
        window.close = function () {
            window.chrome.webview.postMessage('closeTab');
        };
    }

    $('.account-clear-cache').on('click', e => {
        e.preventDefault();
        window.ris.clearCache();
        DevExpress.ui.notify('缓存已清除', 'success', 1000);
    });

    $('.account-change-password').on('click', e => {
        e.preventDefault();
        window.ris.changePassword();
    });
})()